#! /usr/bin/python3
# -*- coding: utf-8 -*-
"""
Created on 2020/1/7 15:22 星期二

@author: jyz
"""
from config.config_setting import *
import time
import requests


# 得到摄像头需要实现的功能,功能列表{安全帽：10，反光衣：20，越界：30，人员聚集：40，摔倒行为检测：50，人员离岗：60，人员徘徊：70，裸土覆盖：80，火焰检测：90}
def get_camera_functions():
    # camera_functions_1 = []
    # camera_functions_2 = []
    # camera_functions_3 = []
    # camera_functions_4 = []
    url = IP + '/fvs/api/alg/device/list'
    r = requests.get(url)
    if r.status_code == 200:
        # print('请求成功')
        pass
    else:
        print('请求失败，重新请求...')
        r = requests.get(url)
    request_content = eval(r.text)['data']['list']
    # request_content = [
    #     {'deviceId': 1, 'name': 's1', 'username': 'admin', 'password': 'fcwl123456', 'srcStreamUrl': 'rtsp://192.168.1.94:554/Streaming/Channels/501',
    #      'config': [{'type': 30, 'rule': {'linePoint': [{'x': 12.12, 'y': 13.12}]}, 'state': 1,
    #                  'timeList': [{'startTime': '07:00', 'endTime': '12:00'}, {'startTime': '14:00', 'endTime': '18:00'}]},
    #                 {'type': 40, 'rule': {'polygonPoint': [{'x': 12.12, 'y': 13.12}, {'x': 14.12, 'y': 15.12}], 'personNum': 50}, 'state': 1,
    #                  'timeList': [{'startTime': '07:00', 'endTime': '12:00'}, {'startTime': '14:00', 'endTime': '18:00'}]}]},
    #
    #     {'deviceId': 2, 'name': 's6', 'username': 'admin', 'password': 'fcwl123456', 'srcStreamUrl': 'rtsp://192.168.1.94:554/Streaming/Channels/601',
    #      'config': [{'type': 30, 'rule': {'linePoint': [{'x': 172.0, 'y': 501.0}]}, 'state': 1,
    #                  'timeList': [{'startTime': '07:00', 'endTime': '12:00'}, {'startTime': '14:00', 'endTime': '18:00'}]},
    #                 {'type': 60, 'rule': {'personNum': 20, 'times': 30}, 'state': 1,
    #                  'timeList': [{'startTime': '07:00', 'endTime': '12:00'}, {'startTime': '14:00', 'endTime': '18:00'}]},
    #                 {'type': 40, 'rule': {'polygonPoint': [{'x': 290.0, 'y': 201.0}, {'x': 536.0, 'y': 273.0}, {'x': 628.0, 'y': 151.0}, {'x': 581.0, 'y': 66.0}], 'personNum': 5}, 'state': 1,
    #                  'timeList': [{'startTime': '07:00', 'endTime': '12:00'}, {'startTime': '14:00', 'endTime': '18:00'}]},
    #                 {'type': 10, 'rule': {}, 'state': 1, 'timeList': [{'startTime': '02:04', 'endTime': '04:05'}]}]},
    #
    #     {'deviceId': 3, 'name': '测试1', 'username': 'admin', 'password': 'fcwl123456', 'srcStreamUrl': 'rtsp://192.168.1.94:554/Streaming/Channels/701',
    #      'config': [{'type': 30, 'rule': {'linePoint': [{'x': 12.12, 'y': 13.12}]}, 'state': 0,
    #                  'timeList': []}]}]
    camera_functions, device_params = [], []
    for device_content in request_content:
        device_id = device_content['deviceId']
        if 'config' in device_content.keys():  # 判断每个设备是否携带了配置参数，若没有，则pass。
            device_config = device_content['config']
            for device_conf in device_config:
                if device_conf['state'] != 0:  # 判断每个设备配置的算法是否状态，如果不可用则pass。
                    try:  # 根据算法名称获取算法需要的参数名
                        device_param = ALGORITHM_PARAMS[device_conf['type']]
                    except:
                        device_param = ''
                    if device_param:
                        device_params = device_conf['rule']
                    if 'timeList' in device_conf.keys():
                        camera_function = DEVICE_ALGORITHM(device_id, device_conf['type'], device_conf['timeList'], device_params)
                    else:
                        camera_function = DEVICE_ALGORITHM(device_id, device_conf['type'], [], device_params)
                    device_params = []
                    camera_functions.append(camera_function)
    return camera_functions


# 得到摄像头需要实现的功能,功能列表{安全帽：10，反光衣：20，越界：30，人员聚集：40，摔倒行为检测：50，人员离岗：60，人员徘徊：70，裸土覆盖：80，火焰检测：90}
def get_camera_function():
    camera_functions_1 = []
    camera_functions_2 = []
    camera_functions_3 = []
    camera_functions_4 = []
    camera_functions_5 = []
    url = 'http://192.168.1.242/fvs/api/alg/device/list'
    r = requests.get(url)
    if r.status_code == 200:
        # print('请求成功')
        pass
    while r.status_code != 200:
        print('请求失败，重新请求...')
        r = requests.get(url)
    request_content = eval(r.text)['data']['list']
    # request_content = [
    #     {'deviceId': 2, 'name': 's6', 'username': 'admin', 'password': 'fcwl123456', 'srcStreamUrl': 'rtsp://192.168.1.94:554/Streaming/Channels/601',
    # 'config': [{'type': 40, 'rule': {'polygonPoint': [{'x': 856, 'y': 290}, {'x': 1200, 'y': 314}, {'x': 1062, 'y': 656}, {'x': 462, 'y': 652}], 'personNum': 50}, 'state': 1,
    #             'timeList': [{'startTime': '07:00', 'endTime': '12:00'}, {'startTime': '14:00', 'endTime': '18:00'}]}]}]
    # 'config': [{"type": 10, "rule": {}, "state": 1, "timeList": [{"startTime": "08:00", "endTime": "12:00"}]},
    #            {"type": 30, "rule": {"linePoint": [{"x": 297.0, "y": 225.0}, {"x": 730.0, "y": 526.0}]}, "state": 1, "timeList": [{"startTime": "08:00", "endTime": "12:00"}, {"startTime": "14:00", "endTime": "16:00"}, {"startTime": "03:00", "endTime": "04:00"}]},
    #            {'type': 40, 'rule': {'polygonPoint': [{'x': 273.0, 'y': 200.0}, {'x': 757.0, 'y': 234.0}, {'x': 753.0, 'y': 469.0}, {'x': 225.0, 'y': 492.0}], 'personNum': 2}, 'state': 1,
    #                         'timeList': [{'startTime': '07:00', 'endTime': '12:00'}, {'startTime': '14:00', 'endTime': '18:00'}]}]}]
    device_ids = [req['deviceId'] for req in request_content]
    camera_configs = [req['config'] for req in request_content]
    linePoint = []
    polygonPoint = []
    personNum = 0
    time_threshold = 0
    for deviceId, camera_config in zip(device_ids, camera_configs):
        for camera_con in camera_config:
            algorithm_type = camera_con['type']
            algorithm_state = camera_con['state']
            if camera_con['rule']:
                if 'personNum' in list(camera_con['rule'].keys()):
                    personNum = camera_con['rule']['personNum']
                if list(camera_con['rule'].keys())[0] == 'linePoint':
                    linePoint = [tuple(i_point.values())[::-1] for i_point in list(camera_con['rule'].values())[0]]
                if list(camera_con['rule'].keys())[0] == 'times':
                    time_threshold = camera_con['rule']['times']
                if list(camera_con['rule'].keys())[0] == 'polygonPoint':
                    polygonPoint = [tuple(i_point.values())[::-1] for i_point in
                                    list(camera_con['rule'].values())[0]]
            if algorithm_type in [10, 20, 50, 80, 90]:  # 不需要超参数的算法
                camera_function1 = {deviceId: [int(algorithm_type) * int(algorithm_state)]}
                camera_functions_1.append(camera_function1)
            elif algorithm_type in [30]:  # 多了直线的坐标点，实现越界检测
                camera_function2 = {deviceId: [int(algorithm_type) * int(algorithm_state), linePoint]}
                camera_functions_2.append(camera_function2)
            elif algorithm_type in [40]:  # 多了坐标点和人数，实现人员聚集算法
                camera_function3 = {deviceId: [int(algorithm_type) * int(algorithm_state), personNum, polygonPoint]}
                camera_functions_3.append(camera_function3)
            elif algorithm_type in [60]:  # 多了人数和时间阈值
                camera_function4 = {
                    deviceId: [int(algorithm_type) * int(algorithm_state), personNum, time_threshold]}
                camera_functions_4.append(camera_function4)
            else:  # 人员徘徊检测，多了多边形的坐标点
                camera_function5 = {deviceId: [int(algorithm_type) * int(algorithm_state), polygonPoint]}
                camera_functions_5.append(camera_function5)
    camera_functions = [camera_functions_1, camera_functions_2, camera_functions_3, camera_functions_4]
    return camera_functions, device_ids


def get_camera_rtspUrl():
    # video_path = rtsp://admin:fcwl123456@192.168.1.94:554/Streaming/Channels/{}
    camera_paths = []
    url = 'http://192.168.1.242/fvs/api/alg/device/list'
    r = requests.get(url)
    request_content = eval(r.text)['data']
    srcStreamUrls = [req['srcStreamUrl'] for req in
                     request_content]  # rtsp://192.168.1.94:554/Streaming/Channels/101
    userNames = [req['username'] for req in request_content]
    passwords = [req['password'] for req in request_content]
    deviceIds = [req['deviceId'] for req in request_content]
    # 得到访问摄像头的rtmp地址
    for srcStreamUrl, userName, password, deviceId in zip(srcStreamUrls, userNames, passwords, deviceIds):
        prefix_srcStreamUrl = srcStreamUrl.split('//')[0]
        back_srcStreamUrl = srcStreamUrl.split('//')[1]
        camera_path = {deviceId: prefix_srcStreamUrl + '//' + userName + ':' + password + '@' + back_srcStreamUrl}
        camera_paths.append(camera_path)
    return camera_paths, deviceIds


t1 = time.time()
get_cameras = get_camera_functions()
print('t1', time.time()-t1)

for ca in get_cameras:
    print(ca)
print('=='*9)
t2 = time.time()
get_camera = get_camera_function()
print('t1', time.time()-t2)

for ca in get_camera:
    print(ca)
print('=='*9)


"""
判断的前提是接口数据的解析结果是亚杰的数据格式

# 判断当前访问得到的参数是否和3秒前访问到的一样,一样则返回True,不一样返回False
def judge_config(pre, cur):
    # 判断每个设备的算法是否一致
    pre_device_alg, cur_device_alg = [(p.id, p.algorithm) for p in pre], [(c.id, c.algorithm) for c in cur]
    if pre_device_alg != cur_device_alg:
        return False
    else:
        for p, c in zip(pre, cur):
            if p.timeList != c.timeList:  # 判断每个算法的时间限制是否一致
                return False
            elif p.params != c.params:  # 判断每个算法的参数是否一致
                return False
            else:
                return True


pre_config = None
while True:
    jc, t1 = True, time.time()
    cur_config = get_camera_functions()
    if pre_config:
        jc = judge_config(pre_config, cur_config)
    else:
        pre_config = cur_config
    if jc is not True:
        print('与上次访问的结果不相同,需重启.')
    time.sleep(3)
    print(time.time()-t1)
"""


pre_config = None
while True:
    jc, t1 = True, time.time()
    cur_config, devi = get_camera_function()
    cur_device_alg, cur_device_alg_tmp = {}, {}
    for device in devi:
        cur_device_alg_tmp.setdefault(device, [])
    for camera_func in cur_config:
        for camera in camera_func:
            cur_device_alg_tmp[list(camera)[0]].append(list(camera.values())[0])
    print(cur_device_alg_tmp)
    if pre_config:
        if pre_config == cur_config:
            print('与上次访问的结果相同')
        else:
            print('与上次访问的结果不相同,需重启.')
    else:
        pre_config = cur_config
    time.sleep(3)
    print(time.time()-t1)

